import axios from 'axios';
//这里定义的函数会被写入VUE的原生代码，外部引用的使用只需要使用this.$commonFunctions.methods
//的方法就可以直接引用
const commonPlugins={
    install(app){
        app.config.globalProperties.$commonFunctions={
            //Method定义，对外部暴露的方法都应该定义为Method
            get_cookies(key){
                const cookies= document.cookie.split(';')
                for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim(); // 清除前导和尾随空格
                console.log("commonPlugins的get_cookie函数里获取的cookie信息： "+cookie+"\n")
                if (cookie.startsWith(key + '=')) {
                    return cookie.substring(key.length + 1); // 提取键值对中的值部分
                    }
                }
                return null; // 如果未找到匹配的 cookie，则返回 null
            },

            async get_user_profiles(login_token){
                return new Promise((resolve, reject) => {
                    const data = {
                        token: login_token,
                    };
                    //如果cookie有值就不调接口
                    if(hasCookie('user_name')&&hasCookie('avatar')&&hasCookie('user_id')){
                        
                        const res={'name':this.get_cookies('user_name').replace(/\"/g,""),'avatar':this.get_cookies('avatar').replace(/\"/g,""),'user_id':this.get_cookies('user_id'),'is_superuser':this.get_cookies('is_superuser')}
                        console.log("Cookie里的用户信息："+JSON.stringify(res));
                        resolve(res); 
                    }else{
                        console.log("commonPlugins的get_user_profiles调用获取用户信息接口前检查login_token= "+data.token)
                    axios.post("/api/get_profiles/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                        if (response.data["code"] == 20000) {
                            console.log("commonPlugins的get_user_profiles调用获取用户信息接口返回 name: " + response.data["data"][0].name);
                            console.log("commonPlugins的get_user_profiles调用获取用户信息接口返回 avatar: " + response.data["data"][0].avatar);
                            const res={'name':response.data["data"][0].name,'avatar':response.data["data"][0].avatar,'user_id':response.data["data"][0].user_id,'is_superuser':response.data["data"][0].is_superuser}
                            resolve(res);
                        }
                        else {
                            resolve(null);
                        }
                    })
                        .catch(error => {
                        reject(error);
                    });
                    }
                });
            },

            async update_profiles(data){
                return new Promise((resolve, reject) => {
                    console.log("调用接口前的参数："+JSON.stringify(data))
                    axios.post("/api/update_user_profiles/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                        if (response.data["code"] == 20000) {
                            console.log('commonPlugins.js的udapte_profiles前端接口返回20000');
                            const res={'code':20000};
                            console.log("commonPlugins.js的udapte_profiles前端接口将要返回的res数据是："+JSON.stringify(res))
                            resolve(res);
                        }
                        else {
                            console.log('commonPlugins.js的udapte_profiles前端接口异常请检查');
                            resolve(null);
                        }
                    })
                        .catch(error => {
                        reject(error);
                    });
                }); 
            },
            
            get_cash_balance(data){
                return new Promise((resolve, reject) => {
                    axios.post("/api/get_cash_balance/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                        if (response.data!=null && response.data!=undefined) {
                            console.log('commonPlugins.js的查看现金余额前端接口get_cash_balance返回20000');
                            const res=response.data;
                            console.log("commonPlugins.js的查询现金余额接口get_cash_balance将要返回的res数据是："+JSON.stringify(res))
                            resolve(res);
                        }
                        else {
                            console.log('commonPlugins.js的查询现金余额前端接口get_cash_balance异常请检查');
                            resolve(null);
                        }
                    })
                            .catch(error => {
                            reject(error);
                        });
                    }); 
            },

            async get_promotion_code(user_id){
                return new Promise((resolve, reject) => {
                   console.log("前端接口get_promotion_code准备执行");
                    //如果cookie有值就不调接口
                    if(hasCookie('pcode')){
                        const res={'promotion_code':this.get_cookies('pcode')}
                        console.log("Cookie里的推广码(PCode)信息："+JSON.stringify(res));
                        resolve(res); 
                    }else{
                        const data = { "contributer_id": user_id };
                        axios.post("/api/get_promotion_code/", data, { withCredentials: true })
                        .then(response => {
                        console.log(response.data)
                            if (response.data["code"] == 20000) {
                                const res={'promotion_code':response.data["data"][0].promotion_code};
                                resolve(res);
                            }
                            else {
                                resolve(null);
                            }
                        })
                            .catch(error => {
                            reject(error);
                         });
                    }
                    });
                },

            //删除cookie
            deleteCookie(name) {
                document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
            },

            async get_coupons(data){
                return new Promise((resolve, reject) => {
                    axios.post("/api/get_coupons/", data, { withCredentials: true })
                    .then(response => {
                    console.log(response.data)
                        if (response.data["code"] == 20000) {
                            resolve(response.data);
                        }
                        else {
                            resolve(response.data);
                        }
                    })
                        .catch(error => {
                        reject(error);
                    });
                     
                });
            },

            async check_bill(data){
                return new Promise ((resolve, reject) => {
                    axios.post("/api/check_bill/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的check_bill返回数据："+JSON.stringify(response.data))
                        resolve(response.data);
                    })
                        .catch(error => {
                        reject(error);
                    });
                }); 
            },

            // 查询数据资产
            async check_assets(data){
                return new Promise ((resolve, reject) => {
                    console.log("check_assets入参检查："+JSON.stringify(data))
                    axios.post("/api/check_assets/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的check_assets返回数据："+JSON.stringify(response.data))
                        resolve(response.data);
                    })
                        .catch(error => {
                        reject(error);
                    });
                }); 
            },

            // 查询词条的点赞和收藏状态
            async check_interactive_status(data){
                console.log("check_interactive_status入参检查："+JSON.stringify(data))
                return new Promise ((resolve, reject) => {
                    axios.post("/api/check_interactive_status/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的check_interactive_status返回数据："+JSON.stringify(response.data))
                        resolve(response.data);
                    })
                        .catch(error => {
                        reject(error);
                    });
                });  
            },

            // 变更词条交易状态
            change_transcation_status(data){
                return new Promise ((resolve, reject) => {
                    console.log("change_transcation_status入参检查："+JSON.stringify(data))
                    axios.post("/api/toogle_words_transcation_status/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的toogle_words_transcation_status返回数据："+JSON.stringify(response.data))
                        resolve(response.data);
                    })
                        .catch(error => {
                        reject(error);
                    });
                });  
            },
       
            // 收藏操作
            favorite(data){
                return new Promise ((resolve, reject) => {
                    console.log("commonPlugins的favorite入参检查："+JSON.stringify(data))
                    if (data.type===1){
                        axios.post("/api/favorite_words/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的favorite返回数据："+JSON.stringify(response.data))
                        resolve(response.data);
                    })
                        .catch(error => {
                        reject(error);
                    });
                    }else if(data.type===2){
                        // 收藏其他类型内容
                        ;
                    }
                });  
            },

            // 取消收藏
            cancel_favorite(data){
                return new Promise ((resolve, reject) => {
                    console.log("commonPlugins的cancel_favorite入参检查："+JSON.stringify(data))
                    axios.post("/api/do_cancel_assets_releationship/", data, { withCredentials: true })
                    .then(response => {
                    console.log("commonPlugins的favorite返回数据："+JSON.stringify(response.data))
                        resolve(response.data.code);
                    })
                        .catch(error => {
                        reject(error);
                    });
                   
                });  
            },

            // 查询是否有cookie的值
            anyCookie(key){
              return  hasCookie(key)
            }
        }
        //不对外暴露的内部方法应该是function开头
        //定义方法为function __function_name()__{……}
        function hasCookie(key){
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // 判断 cookie 键是否匹配
                if (cookie.startsWith(key + '=')) {
                return true; // 找到匹配的 cookie 键
                }
            }
            return false; // 未找到匹配的 cookie 键
        }
    }
};
export default commonPlugins;